/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.cfg.bd;

import cn.easyplatform.cfg.BusinessDateHandler;
import cn.easyplatform.dao.BizDao;
import cn.easyplatform.dos.FieldDo;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.type.FieldType;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class StdCreditBusinessDateHandler implements BusinessDateHandler {

	private CommandContext cc;
	
	private final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
	
	private final Calendar calendar = Calendar.getInstance();

	StdCreditBusinessDateHandler(CommandContext cc) {
		this.cc = cc;
	}

	@Override
	public boolean isBusinessDate(Date date, String ccy) {
		BizDao dao = cc.getBizDao();
		//
		if(date == null)
			return false;
		FieldDo param = new FieldDo(FieldType.VARCHAR);
		param.setValue(ccy);
		List<FieldDo> parameter = new ArrayList<FieldDo>();
		parameter.add(param);
		List<FieldDo[]> holidays = dao.selectList("select holiday,type from Holiday where currency=?", parameter);
		if (holidays == null) {
			//判断是否是周末
			calendar.setTime(date);
			int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
			if (dayOfWeek == Calendar.SUNDAY
					|| dayOfWeek == Calendar.SATURDAY) {
				return false;
			}
            return true;
		}
		else{
			String date1 = sdf.format(date);
			for(FieldDo[] holiday:holidays){
				if(holiday[0].getValue() instanceof Date){
					String date2 = sdf.format((Date)holiday[0].getValue());
					if(holiday[1].getValue() instanceof String){
						String type = (String)holiday[1].getValue();
						//节假日
						if(type.equals("Y") && date1.equals(date2))
						{
							return false;
						}
						//特殊工作日
						else if(type.equals("N") && date1.equals(date2))
						{
							return true;
						}
					}
				}
			}
			
			//判断是否是周末
			calendar.setTime(date);
			int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
			if (dayOfWeek == Calendar.SUNDAY
					|| dayOfWeek == Calendar.SATURDAY) {
				return false;
			}
		}
		return true;
	}

}
